package com.red.listener.redis;

import com.red.common.JsonUtil;
import com.red.dao.GoodsSellRepository;
import com.red.dao.OrdersRepository;
import com.red.entity.GoodsSell;
import com.red.entity.Orders;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.connection.MessageListener;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Objects;

/**
 * @program: SpringBootDemos
 * @description: redis监听器
 * @author: Kangsen
 * @create: 2021-09-18 14:09
 **/
@Service(value = OrderRedisListener.SERVICE_NAME)
@Slf4j
public class OrderRedisListener implements MessageListener {

    public static final String SERVICE_NAME = "com.red.listener.redis.OrderRedisListener";

    @Autowired
    private OrdersRepository ordersRepository;

    @Autowired
    private GoodsSellRepository goodsSellRepository;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void onMessage(Message message, byte[] bytes) {
        log.info(">>>>>>>>>>>>>>>redis监听消息>>>>>>>>>>>>>>>>>>>");
        String expireKey = new String(message.getBody());
        log.error("缓存【{}】失效",expireKey);
        //获取订单号
        String tradeNo = expireKey.substring(expireKey.indexOf("_") + 1);
        log.info("订单号：{}",tradeNo);
        String orderObject = JsonUtil.objectToJson(ordersRepository.findOrderByTradeNo(tradeNo));
        Orders order = ordersRepository.findOrderByTradeNo(tradeNo);
        if(Objects.isNull(order)){
            log.error("没找到这个订单，处理不了！");
            return;
        }
        log.info("orderObject : {}",orderObject);
        //设置订单失效
        int startPos = ordersRepository.setStatusByOrderId(2, Long.valueOf(order.getId()));
        if(startPos>0){
            //处理
            GoodsSell orderByOrderId = goodsSellRepository.findOrderByOrderId(order.getId());
            log.info(" goodsSell => {}",JsonUtil.objectToJson(orderByOrderId));
            //goodsSellRepository.setStatusByGoodsId(2,order.get)
            log.info("订单处理成功!");
        }else{
            log.error("订单处理失败!");
        }
    }
}
